<template>
  <div class="amap">
    <!-- 地图容器 -->
    <div ref="amap" class="amap_view"></div>
    <div id="panel"></div>
    <!-- 搜索栏 -->
    <el-input id="map_input" v-model.trim="qiVal" placeholder="请输入起点" size="large"
      class="qi custom-input-style"></el-input>
    <el-input id="map_input" v-model.trim="zhVal" placeholder="请输入终点" size="large"
      class="zh custom-input-style"></el-input>
    <div class="mid">
      <el-tag v-for="tag in dynamicTags" :key="tag" closable style="margin: 5px" :disable-transitions="false"
        @close="handleClose(tag)">
        {{ tag }}
      </el-tag>
      <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
        @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
      <el-button v-else class="button-new-tag" size="small" @click="showInput">
        + 添加途径点
      </el-button>
    </div>
    <el-button type="success" :icon="Check" circle class="success" @click="gofind" size="large" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, nextTick } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { Check } from '@element-plus/icons-vue'
import { ElInput } from 'element-plus'


//途径点
const inputValue = ref('')
const dynamicTags = ref<string[]>([])

const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const amap = ref(null)
const qiVal = ref('')
const zhVal = ref('')
let drivings = ref(null)
let map: any = null

onMounted(() => {
  loadAMap()
})

import { ElMessage } from 'element-plus'
const gofind = () => {
  if (qiVal.value && zhVal.value) {
    // 清除地图上所有添加的覆盖物
    map.clearMap()
    var points = []
    points.push({ keyword: qiVal.value })

    for (let i = 0; i < dynamicTags.value.length; i++) {
      points.push({
        keyword: dynamicTags.value[i]
      })
    }
    points.push({
      keyword: zhVal.value
    })
    //console.log(points);

    // 确保 drivings.value 已经被初始化

    (drivings.value as any).search(points, function (status: any, result: any) {
      if (status === 'complete') {
        if (result.routes && result.routes.length) {
          //console.log('绘制驾车路线完成');
        }
      } else {
        //console.log('绘制驾车路线失败');
      }
    });

  } else {
    ElMessage({
      message: '起点或终点不能为空！',
      type: 'warning'
    })
  }
}
const loadAMap = () => {
  (AMapLoader as any).reset()

  AMapLoader.load({
    key: 'c7317e56d00520642ad9b6c86e9e6b48' /* Web端JS API key */,
    version: '2.0',
    plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.Geolocation']
  })
    .then((AMap) => {
      initMap(AMap)
    })
    .catch((e) => {
      console.error(e)
    })
}

const initMap = (AMap: any) => {
  map = new AMap.Map(amap.value, {
    resizeEnable: true /* 城市定位 */,
    // center: [116.397428, 39.90923], //地图中心点
    zooms: [1, 18],
    zoom: 14
  })

  // // 比例尺
  map.addControl(new AMap.Scale())

  AMap.plugin('AMap.Geolocation', function () {
    var geolocation = new AMap.Geolocation({
      enableHighAccuracy: true, //是否使用高精度定位，默认:true
      maximumAge: 0, //定位结果缓存0毫秒，默认：0
      convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
      showButton: true, //显示定位按钮，默认：true
      buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
      buttonOffset: new AMap.Pixel(10, 20),
      showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
      showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
      panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
      zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
    })
    map.addControl(geolocation)
    geolocation.getCurrentPosition()
  })

  AMap.plugin('AMap.Driving', function () {
    var driving = new AMap.Driving({
      policy: 0, //驾车路线规划策略，0是速度优先的策略
      panel: 'panel',
      map: map,
    })
    drivings.value = driving

  })
}


onBeforeUnmount(() => {
  (AMapLoader as any).reset()
  map && map.destroy()
  map = null
})
</script>

<style scoped lang="less">
#panel {
  position: fixed;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 10%;
  right: 10px;
  width: 280px;
}

#panel .amap-call {
  background-color: #009cf9;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

#panel .amap-lib-driving {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  overflow: hidden;
}

.amap {
  width: 100%;
  height: 100vh;
  border: 1px solid #ccc;
  position: relative;
  font-size: 25px;

  .amap_view {
    width: 100%;
    height: 100%;
  }

  .qi {
    width: 200px;
    position: absolute;
    top: 15%;
    left: 5%;
    background-color: bisque;
  }

  .zh {
    width: 200px;
    position: absolute;
    top: 15%;
    left: 20%;
  }

  .mid {
    position: absolute;
    top: 22%;
    left: 5%;
    width: 300px;
    height: 100px;
    background-color: #fff1b9;

    .button-new-tag {
      margin: 10px;
    }
  }

  .success {
    position: absolute;
    top: 15%;
    left: 35%;

  }
}


div/deep/ .custom-input-style .el-input__wrapper {
  background-color: #fff1b9 !important;
}

// div/deep/  .el-input__inner::placeholder {color:  #000;
// }</style>
